package com.young.jdbc.datasource;

import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;

/**
 * @Author: young
 * @Date: 2021-12-03 21:21
 * @Description:
 */
public class JdbcUtilsByDruid_Use {
	// Druid数据库连接池封装的工具类
	@Test
	public void testSelect(){
		Connection connection = null;
		String sql = "select * from student where id=?";
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = JdbcUtilsByDruid.getConnection();
			System.out.println(connection.getClass()); //运行类型
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1,1);
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()){
				int id = resultSet.getInt(1);
				String name = resultSet.getString(2);
				String sex = resultSet.getString(3);
				Date birthday = resultSet.getDate(4);
				String mobile = resultSet.getString(5);
				System.out.println(id+"\t"+name+"\t"+sex+"\t"+birthday+"\t"+mobile);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtilsByDruid.close(resultSet,preparedStatement,connection);
		}
	}
	
	// 使用土方法来解决ResultSet =封装=> ArrayList
	@Test
	public ArrayList<Student> testSelectToArrayList(){
		Connection connection = null;
		String sql = "select * from student";
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		// 创建ArrayList对象，存放student对象
		ArrayList<Student> list = new ArrayList<>();
		try {
			connection = JdbcUtilsByDruid.getConnection();
			System.out.println(connection.getClass()); //运行类型
			preparedStatement = connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()){
				int id = resultSet.getInt(1);
				String name = resultSet.getString(2);
				String sex = resultSet.getString(3);
				Date birthday = resultSet.getDate(4);
				String phone = resultSet.getString(5);
				// 把得到的resultSet的记录，封装到Student对象，放到list集合
				list.add(new Student(id,name,sex,birthday,phone));
			}
			// System.out.println("list集合数据："+list);
			for (Student student : list){
				System.out.println("id="+student.getId()+"\t"+student.getName());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtilsByDruid.close(resultSet,preparedStatement,connection);
		}
		// 因为ArrayList和Connection没有任何关联，所有该集合可以复用
		return list;
	}
}
